//
//  StoreInformationViewModel.m
//  GLGW_Shoping
//
//  Created by whx on 2018/12/10.
//  Copyright © 2018年 yang. All rights reserved.
//

#import "StoreInformationViewModel.h"
#import "PostsTableViewCell.h"
#import "StoreInformationTwoHeaderView.h"
#import "NoDataFootTableViewHeaderFooterView.h"
#import "StoreInformationOneTableViewCell.h"
#import "StoreInformationOneHearderView.h"
#import "StoreInformationTwoTableViewCell.h"
#import "StoreInformationThreeTableViewCell.h"
#import "StoreInformationFourTableViewCell.h"
#import "StoreInformationFiveTableViewCell.h"
#import "StoreInformationSixTableViewCell.h"
#import "StoreInformationSevenTableViewCell.h"
#import "MainTypesListNextSteelMillsModel.h"
#import "MyStoreInformationNameModel.h"
#import "MyStoreInformationModel.h"
#import "MainTypesListNextModel.h"
#import "MainArealCitysModel.h"
#import "MainTypesListModel.h"
#import "MainAreaModel.h"
#import "LoginModel.h"
#import "StoreDataAlertView.h"
#import "OrderOperationView.h"

@interface StoreInformationViewModel ()<UITableViewDelegate, UITableViewDataSource, UITextViewDelegate, UITextFieldDelegate>
{
    UITableView *selfTableView;
    NSArray *leftConnectArr;
//    NSString *textFStr;            // 店铺名称字符
    NSString *mainArea;            // 主营区域字符
}

@property (nonatomic, strong) NSMutableArray *shopAdvantageArr;   // 店铺优势
@property (nonatomic, strong) NSMutableArray *connectArr;         // 联系人信息
@property (nonatomic, strong) MyStoreInformationModel *model;     // 返回数据模型

@end

@implementation StoreInformationViewModel

- (instancetype)initWithViewToViewModel:(UITableView *)tableView theSuperView:(UIView *)superView
{
    if (self = [super initWithViewToViewModel:tableView theSuperView:superView]) {
        leftConnectArr = @[@"请输入业务联系人", @"请输入手机", @"请输入固话", @"请输入传真", @"请输入QQ"];
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.backgroundColor = [UIColor colorWithHexString:@"#F2F2F2"];
        tableView.sectionFooterHeight = 0.0;
        tableView.sectionHeaderHeight = 10.0;
        tableView.mj_header.hidden = YES;
        tableView.mj_footer.hidden = YES;
        [tableView registerClass:[NoDataFootTableViewHeaderFooterView class] forHeaderFooterViewReuseIdentifier:@"NoDataFootTableViewHeaderFooterView"];
        [tableView registerClass:[StoreInformationOneHearderView class] forHeaderFooterViewReuseIdentifier:@"StoreInformationOneHearderView"];
        [tableView registerClass:[StoreInformationTwoHeaderView class] forHeaderFooterViewReuseIdentifier:@"StoreInformationTwoHeaderView"];
        selfTableView = tableView;
        [superView addSubview:tableView];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(stateChange:) name:@"kMainTypeList" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(mainArealList:) name:@"kMainArealList" object:nil];
        self.model = [MyStoreInformationModel new];
        // 请求数据资料，是否注册过店铺
        [self requestSoreInormation];
    }
    return self;
}

- (void)stateChange:(NSNotification *)notification
{
    NSDictionary * dic = notification.object;
//    DLog(@"==]]]:::%@",dic);
    MyStoreInformationProsAndFactory *factory = [MyStoreInformationProsAndFactory new];
    if (dic[@"one"]) {
        MainTypesListArrModel *model = dic[@"one"];
        factory.categoryName = model.categoryName;
    }
    if (dic[@"two"]) {
        NSDictionary *liDic = dic[@"two"];
        if (liDic[@"arr"]) {
            NSArray *arr = liDic[@"arr"];
            NSMutableString *muStr = [NSMutableString string];
            for (int i = 0; i < arr.count; i ++) {
                MainTypesListNextArrModel *model = arr[i];
                if (i == arr.count - 1) {
                    [muStr appendFormat:@"%@",model.productName];
                } else {
                    [muStr appendFormat:@"%@,",model.productName];
                }
            }
            factory.productName = muStr;
        }
    }
    if (dic[@"three"]) {
        NSArray *arr = dic[@"three"];
        NSMutableString *muStr = [NSMutableString string];
        for (int i = 0; i < arr.count; i ++) {
            MainTypesListNextSteelMillsArrModel *model = arr[i];
            if (i == arr.count - 1) {
                [muStr appendFormat:@"%@",model.factoryName];
            } else {
                [muStr appendFormat:@"%@,",model.factoryName];
            }
        }
        factory.factoryName = muStr;
    }
    if (self.model.prosAndFactorys.count <= 0) {
        self.model.prosAndFactorys = [NSMutableArray array];
    }
    // 判断，选取的主营类型以前有选择过，则删掉原来的选择
    for (int i = 0; i < self.model.prosAndFactorys.count; i ++) {
        MyStoreInformationProsAndFactory *liFactory = self.model.prosAndFactorys[i];
        if ([liFactory.categoryName isEqualToString:factory.categoryName]) {
            [self.model.prosAndFactorys removeObjectAtIndex:i];
        }
    }
    [self.model.prosAndFactorys addObject:factory];
    [selfTableView reloadSections:[NSIndexSet indexSetWithIndex:2]  withRowAnimation:UITableViewRowAnimationAutomatic];
}

// 处理选择好的主营区域的数据
- (void)mainArealList:(NSNotification *)notification
{
    NSDictionary * dic = notification.object;
    if (!dic) return;
    NSMutableArray *wArr = [NSMutableArray array];
    MyStoreInformationMainArealModel *arealModel = [MyStoreInformationMainArealModel new];
    NSArray *arr = dic[@"arr"];
    if (arr.count <= 0) return;
    for (int i = 0; i < arr.count; i ++) {
        NSDictionary *liDic = arr[i];
        NSArray *citysArr = [NSArray arrayWithArray:liDic[@"four"]];
        if (citysArr.count > 0) {
            MainAreaListModel *areaListModel = liDic[@"two"];
            NSMutableArray *cicysNewArr = [NSMutableArray array];
            for (int i = 0; i < citysArr.count; i ++) {
                MainArealCitysListModel *citysListModel = citysArr[i];
                [cicysNewArr addObject:citysListModel.cityName];
            }
            arealModel.province = areaListModel.provinceName;
            arealModel.citys = [NSMutableArray arrayWithArray:cicysNewArr];
            [wArr addObject:arealModel];
        }
    }
    self.model.mainArea = [NSMutableArray arrayWithArray:wArr];
    NSIndexPath *index = [NSIndexPath indexPathForRow:0 inSection:1];
    [selfTableView reloadRowsAtIndexPaths:@[index] withRowAnimation:UITableViewRowAnimationAutomatic];
}

#pragma mark-tableViewDelegate And tableViewDataSource
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 3 || section == 4 || section == 5) {
        return kHeightProportion_In_iPhoneTriploid(10);
    }
    else if (section == 2) {
        return kHeightProportion_In_iPhoneTriploid(14);
    }
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 2 || section == 3) {
        if (self.model.prosAndFactorys.count > 0) {
            return kHeightProportion_In_iPhoneTriploid(2) + kHeightProportion_In_iPhoneTriploid(43);
        }
        return kHeightProportion_In_iPhoneTriploid(43);
    } else if (section == 3) {
        if (self.shopAdvantageArr.count > 0) {
            return kHeightProportion_In_iPhoneTriploid(16) + kHeightProportion_In_iPhoneTriploid(43);
        }
        return kHeightProportion_In_iPhoneTriploid(43);
    } else if (section == 4 || section == 5) {
        return kHeightProportion_In_iPhoneTriploid(42);
    }
    return kHeightProportion_In_iPhoneTriploid(0.01);
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    NoDataFootTableViewHeaderFooterView *footer = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"NoDataFootTableViewHeaderFooterView"];
    if (section == 2) {
        footer.bgColor = [UIColor whiteColor];
    } else {
        footer.bgColor = [UIColor colorWithHexString:@"#F2F2F2"];
    }
    return footer;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    NoDataFootTableViewHeaderFooterView *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"NoDataFootTableViewHeaderFooterView"];
    kWeakSelf(self);
    if (section == 2 ) {
        StoreInformationOneHearderView *headerV = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"StoreInformationOneHearderView"];
        headerV.BlockBtn = ^(GLGWButton *btn) {
            [weakself seleMainType];
        };
        headerV.leftStr = @"主营类型";
        return headerV;
    } else if (section == 3) {
        StoreInformationOneHearderView *headerV = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"StoreInformationOneHearderView"];
        headerV.leftStr = @"店铺优势";
        headerV.BlockBtn = ^(GLGWButton *btn) {
            [weakself addMianType];
        };
        return headerV;
    } else if (section == 4) {
        StoreInformationTwoHeaderView *headeV = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"StoreInformationTwoHeaderView"];
        return headeV;
    } else if (section == 5) {
        StoreInformationTwoHeaderView *headeV = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"StoreInformationTwoHeaderView"];
        headeV.leftStr = @"店铺介绍";
        return headeV;
    }
    return header;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 6;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 2) {
        if (self.model.prosAndFactorys.count <= 0) {
            return 1;
        }
        return self.model.prosAndFactorys.count;
    } else if (section == 4) {
        return leftConnectArr.count;
    } else {
        return 1;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    BaseTableViewCell *cell;
    kWeakSelf(self);
    switch (indexPath.section) {
        case 0: {
            StoreInformationOneTableViewCell *deCell = [StoreInformationOneTableViewCell cellWithTableView:tableView];
            if (self.model.shopName.length > 0) {
                deCell.leftStr = self.model.shopName;
            }
            @weakify(self);
            [deCell.textF.rac_textSignal subscribeNext:^(NSString* text){
                DLog(@"%@",text);
                @strongify(self);
                if (text.length > 15) {
                    NSString *cutStr = [text substringToIndex:15];
                    deCell.textF.text = cutStr;
                    self.model.shopName = cutStr;
                } else {
                    deCell.textF.text = text;
                    self.model.shopName = text;
                }
            }];
            cell = deCell;
        }
            break;
        case 1: {
            StoreInformationTwoTableViewCell *deCell = [StoreInformationTwoTableViewCell cellWithTableView:tableView];
            if (self.model.isRegist == 0) {
                NSArray *arr = [NSArray arrayWithArray:self.model.mainArea];
                if (arr.count > 0) {
                    NSMutableArray *muArr = [NSMutableArray array];
                    for (int i = 0; i < arr.count; i ++) {
                        MyStoreInformationMainArealModel *arealModel = arr[i];
                        for (int i = 0; i < arealModel.citys.count; i ++) {
                            NSString *cityStr = arealModel.citys[i];
                            NSString *appedStr = [NSString stringWithFormat:@"%@%@",arealModel.province,cityStr];
                            [muArr addObject:appedStr];
                        }
                    }
                    deCell.detailStrArr = [NSMutableArray arrayWithArray:muArr];
                }
            }
            cell = deCell;
        }
            break;
        case 2: {
            if (self.model.prosAndFactorys.count <= 0) {
                StoreInformationSevenTableViewCell *deCell = [StoreInformationSevenTableViewCell cellWithTableView:tableView];
                cell = deCell;
            } else {
                StoreInformationThreeTableViewCell *deCell = [StoreInformationThreeTableViewCell cellWithTableView:tableView];
                deCell.model = self.model.prosAndFactorys[indexPath.row];
                deCell.index = indexPath;
                deCell.BlcokDelete = ^(GLGWButton *btn, NSIndexPath *index) {
                    [weakself alertViewIndex:index];
                };
                cell = deCell;
            }
        }
            break;
        case 3: {
            if (self.shopAdvantageArr.count <= 0) {
                StoreInformationSevenTableViewCell *deCell = [StoreInformationSevenTableViewCell cellWithTableView:tableView];
                cell = deCell;
            } else {
                StoreInformationFourTableViewCell *deCell = [StoreInformationFourTableViewCell cellWithTableView:tableView];
                deCell.dataArr = self.shopAdvantageArr;
                deCell.BlockTapTagsView = ^(UIButton *btn, NSInteger tag) {
                    [weakself tapTagsView:btn tags:tag];
                };
                cell = deCell;
            }
        }
            break;
        case 4: {
            StoreInformationFiveTableViewCell *deCell = [StoreInformationFiveTableViewCell cellWithTableView:tableView];
            deCell.textFild.tag = 765 + indexPath.row;
            @weakify(self);
            [deCell.textFild.rac_textSignal subscribeNext:^(NSString * _Nullable x) {
                @strongify(self);
                [self rac_textfildChange:deCell.textFild textStr:x];
            }];
            if ([self.connectArr[indexPath.row] length]  <= 0) {
                deCell.textFild.placeholder = leftConnectArr[indexPath.row];
            } else {
                deCell.textFild.text = [NSString stringWithFormat:@"%@",self.connectArr[indexPath.row]];
            }
            if (indexPath.row == 0) {
            } else if (indexPath.row == 3){
                deCell.textFild.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
            } else {
                deCell.textFild.keyboardType = UIKeyboardTypeNumberPad;
            }
            cell = deCell;
        }
            break;
        case 5: {
            StoreInformationSixTableViewCell *deCell = [StoreInformationSixTableViewCell cellWithTableView:tableView];
            if (self.model.introductions) {
                deCell.textView.text = self.model.introductions;
            }
            [deCell.textView.rac_textSignal subscribeNext:^(NSString *x) {
                if (x.length > 500) {
                    NSString *cutStr = [x substringToIndex:500];
                    deCell.textView.text = cutStr;
                    self.model.introductions = cutStr;
                } else {
                    deCell.textView.text = x;
                    self.model.introductions = x;
                }
            }];

            cell = deCell;
        }
            break;
        default:{}
            break;
    }
    if (indexPath.section == 4) {
        [cell hiderLine:NO];
        [cell setSepartionLineWith:lineModel_Half];
    } else {
        [cell hiderLine:YES];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1) {
        if (self.BlockSelectRow) {
            self.BlockSelectRow(indexPath);
        }
    }
}

// 主营类型添加按钮
- (void)seleMainType
{
    if (self.BlockMainType) {
        self.BlockMainType();
    }
}

// 添加店铺优势按钮
- (void)addMianType
{
    StoreDataAlertView *alerV = [[StoreDataAlertView alloc] initStoreDataAlertView];
    kWeakSelf(self);
    alerV.BlockSure = ^(NSString *textStr) {
        [weakself refreshDataWithStr:textStr];
    };
    alerV.BlockCancel = ^(GLGWButton *btn) {};
}

// 添加店铺优势
- (void)refreshDataWithStr:(NSString *)str
{
    if (str.length <= 0) return;
    [self.shopAdvantageArr insertObject:str atIndex:0];
    [selfTableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:3]] withRowAnimation:UITableViewRowAnimationNone];
    // 这里高度需要变化
}

- (void)rac_textfildChange:(UITextField *)textF textStr:(NSString *)str
{
    switch (textF.tag) {
        case 765: // 业务联系人
            self.model.contacts = str;
            break;
        case 766: // 手机
            self.model.contactPhone = str;
            break;
        case 767: // 固话
            self.model.contactTel = str;
            break;
        case 768: // 传真
            self.model.fax = str;
            break;
        case 769: // QQ
            self.model.contactQQ = str;
            break;
        default:
            break;
    }
}

- (void)alertViewIndex:(NSIndexPath *)index
{
    OrderOperationView * opeartionView = [[OrderOperationView alloc] initWithPopOrderOperation:@[@"确定",@"取消"] theTitleStr:@"" theTosStr:@"您确定要删除主营类型的内容？"];
    [opeartionView show];
    opeartionView.Block_CaseAction = ^(NSInteger tag) {
        if (tag == 310) {
            [self mainTypeData:index];
        }
    };
}

- (void)mainTypeData:(NSIndexPath *)index
{
    [self.model.prosAndFactorys removeObjectAtIndex:index.row];
    [selfTableView reloadSections:[NSIndexSet indexSetWithIndex:2] withRowAnimation:UITableViewRowAnimationAutomatic];
}

- (void)tapTagsView:(UIButton *)btn tags:(NSInteger)tag
{
    NSInteger num = btn.tag - 784843;
    [self.shopAdvantageArr removeObjectAtIndex:num];
    NSIndexPath *index = [NSIndexPath indexPathForRow:0 inSection:3];
    [selfTableView reloadRowsAtIndexPaths:@[index] withRowAnimation:UITableViewRowAnimationAutomatic];
}

- (void)keepAll
{
    if (self.model.shopName.length <= 0) {
        DLog(@"店铺名不能为空");
        return;
    }
    // 判断主营区域
    // 判断主营类型
    // 判断店铺优势
    [self requestShopName];
    
//    [self requestAddStoreInformation];
}

#pragma mark - 懒加载
- (NSMutableArray *)shopAdvantageArr
{
    if (!_shopAdvantageArr) {
        _shopAdvantageArr = [NSMutableArray array];
    }
    return _shopAdvantageArr;
}


#pragma mark - 请求接口
// 店铺名称是否可用
- (void)requestShopName
{
    NSDictionary *param = @{@"shopName": koString(self.model.shopName)};
    [GLGWRequestTool POST:[NSString stringWithFormat:@"%@%@",kApiPrefix,kNameAble] lodingView:nil lodingTextString:@"" isLoding:YES parameters:param success:^(id  _Nullable response) {
        MyStoreInformationNameModel *nameModel = [MyStoreInformationNameModel yy_modelWithJSON:response];
        if (nameModel.data.isUsed == 0) { // 1：未使用 0 ：已使用
            [self requestAddStoreInformation];
        } else {
            OrderOperationView * opeartionView = [[OrderOperationView alloc] initWithPopOrderOperation:@[@"确定"] theTitleStr:@"" theTosStr:@"店铺名称不能与其他店铺重复"];
            [opeartionView show];
            opeartionView.Block_CaseAction = ^(NSInteger tag) {
//                if (tag == 310) {
//                }
            };
        }

    } failure:^(NSError * _Nullable error) {}];
}

// 添加店铺资料 yes:是第一次保存 no:修改
- (void)requestAddStoreInformation
{
    if (self.userInforData.length == 0) return;
    NSMutableString *muStr = [NSMutableString string];
    for (int i = 0; i < self.shopAdvantageArr.count; i ++) {
        NSString *str;
        if (i == self.shopAdvantageArr.count - 1) {
            str = [NSString stringWithFormat:@"%@",self.shopAdvantageArr[i]];
        } else {
            str = [NSString stringWithFormat:@"%@,",self.shopAdvantageArr[i]];
        }
        [muStr appendString:str];
    }
    NSMutableString *productStr = [NSMutableString string];
    NSMutableString *categoryStr = [NSMutableString string];
    for (int i = 0; i < self.model.prosAndFactorys.count; i ++) {
        MyStoreInformationProsAndFactory *model = self.model.prosAndFactorys[i];
        NSString *str = [NSString stringWithFormat:@"%@:%@-->%@",model.categoryName,model.productName,model.factoryName];
        if (i == self.model.prosAndFactorys.count - 1) {
            [productStr appendFormat:@"%@",str];
            [categoryStr appendFormat:@"%@",model.categoryName];
        } else {
            [productStr appendFormat:@"%@#",str];
            [categoryStr appendFormat:@"%@,",model.categoryName];
        }
    }
    NSMutableArray *areaArr = self.model.mainArea;
    NSMutableArray *areaMuArr = [NSMutableArray array];
    NSDictionary *dic;
    for (int i = 0; i < areaArr.count; i ++) {
        MyStoreInformationMainArealModel *arelModel = areaArr[i];
        dic = @{
                @"province" : arelModel.province,
                @"citys" : arelModel.citys
                };
        [areaMuArr addObject:dic];
    }
    LoginModel *modle = [NSKeyedUnarchiver unarchiveObjectWithData:self.userInforData];
    NSDictionary * param = @{
                           @"userId" : koString(modle.data.userId),
                           @"shopName" : koString(self.model.shopName),             // 店铺名称
                           @"shopType" : @"2",
                           @"enterpriseType" : @2,
                           @"mainArea" : areaMuArr,                                 // 主营区域
                           @"mainCategory" : koString(categoryStr),                 // 主营类型
                           @"mainProduct" : koString(productStr),                   // 拼接好的主营类型
                           @"shopAdvantage" : koString(muStr),                      // 店铺优势
                           @"contacts" : koString(self.model.contacts),             // 联系人
                           @"contactPhone" : koString(self.model.contactPhone),     // 联系人手机
                           @"contactTel" : koString(self.model.contactTel),         // 固话
                           @"fax" : koString(self.model.fax),                       // 传真
                           @"contactQQ" : koString(self.model.contactQQ),           // qq
                           @"introductions" : koString(self.model.introductions)    // 店铺简介
                           };
//    NSLog(@"%@",param);
    NSString *urlStr = kAddStoreInfor;
    if (self.model.isRegist == 1) {
        urlStr = kUpdateStoreInfor;
    }
    [GLGWRequestTool POST:[NSString stringWithFormat:@"%@%@",kApiPrefix,urlStr] lodingView:nil lodingTextString:@"" isLoding:YES parameters:param success:^(id  _Nullable response) {
        NSDictionary * dic = response;
        NSDictionary *messageCode = [dic objectForKey:@"data"];
        if ([[messageCode objectForKey:@"isRegist"] intValue] == 1) {  // 为空，添加
            
        }
    } failure:^(NSError * _Nullable error) {
        DLog(@"====%@",error);
    }];
}

// 店铺资料数据接口
- (void)requestSoreInormation
{
    if (self.userInforData.length == 0) return;
    LoginModel *modles = [NSKeyedUnarchiver unarchiveObjectWithData:self.userInforData];
    NSDictionary * dic = @{@"userId" : koString(modles.data.userId), @"shopType" : @"2"};

    [GLGWRequestTool POST:[NSString stringWithFormat:@"%@%@",kApiPrefix,kStoreInfor] lodingView:nil lodingTextString:@"" isLoding:YES parameters:dic success:^(id  _Nullable response) {
        NSDictionary * dic = response;
        NSDictionary *messageCode = [dic objectForKey:@"data"];
        [self makeData:messageCode];
    } failure:^(NSError * _Nullable error) {
        DLog(@"店铺资料=%@",error);
    }];
}

- (void)makeData:(NSDictionary *)messageCode
{
    self.model = [MyStoreInformationModel yy_modelWithJSON:messageCode];
    NSString *str = [NSString stringWithFormat:@"%@",self.model.shopAdvantage];
    if([str rangeOfString:@","].location != NSNotFound) {
        self.shopAdvantageArr = [NSMutableArray arrayWithArray:[str componentsSeparatedByString:@","]];
    }
    self.connectArr = [NSMutableArray arrayWithObjects:koString(self.model.contacts),koString(self.model.contactPhone), koString(self.model.contactTel),koString(self.model.fax),koString(self.model.contactQQ), nil];
    [self->selfTableView reloadData];
}

@end
